/*
 * Copyright (C), 2002-2016, 上海亦寻信息技术有限公司
 * FileName: PinController.java
 * Author:   linyao
 * Date:     2016-6-24 下午3:45:18
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.emm.yixun.website.controller.marketing;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.emm.yixun.common.model.*;
import com.emm.yixun.common.model.dto.*;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.marketing.service.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.emm.yixun.common.model.enums.DealCategoryEnum;
import com.emm.yixun.common.model.enums.DecorationPaymentMethodEnum;
import com.emm.yixun.common.model.enums.DocTypeEnum;
import com.emm.yixun.common.model.enums.HousingFundTypeEnum;
import com.emm.yixun.common.model.enums.PaymentMethodEnum;
import com.emm.yixun.common.model.enums.ReceivablesTypeEnum;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.customer.service.PayDepositServiceFacade;
import com.emm.yixun.customer.service.SignedServiceFacade;
import com.emm.yixun.customer.service.SubscribeServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.common.utils.NumberToCN;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.vo.common.ExtResultVo;
import com.emm.yixun.website.vo.proceeds.PayDepositDetailVo;
import com.emm.yixun.website.vo.proceeds.SignedDetailVo;
import com.emm.yixun.website.vo.proceeds.SubscribeDetailVo;

/**
 * 〈一句话功能简述〉 〈功能详细描述〉
 * 
 * @author linyao
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/marketing/proceeds/")
public class ProceedsController extends BaseController<Object> {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private PayDepositServiceFacade payDepositServiceFacade;
	@Autowired
	private SubscribeServiceFacade subscribeServiceFacade;
	@Autowired
	private SignedServiceFacade signedServiceFacade;
	@Autowired
	private HaveReceiveRefundServiceFacade haveReceiveRefundServiceFacade;
	@Autowired
	private HaveAdvanceRefundServiceFacade haveAdvanceRefundServiceFacade;
	@Autowired
	private ProceedsServiceFacade proceedsServiceFacade;
	@Autowired
	private UserServiceFacade userServiceFacade;
	@Autowired
	private NeedReceiveRefundServiceFacade needReceiveRefundServiceFacade;
	@Autowired
	private NeedAdvanceRefundServiceFacade needAdvanceRefundServiceFacade;
	@Autowired
	private ReserveAreaServiceFacade reserveAreaServiceFacade;
	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	@Autowired
	private CustomerServiceFacade customerServiceFacade;
	
	/**
	 * 进入认筹收款界面
	 * @return
	 */
	@RequestMapping("deposit")
	public ModelAndView deposit(PayDepositDto payDepositDto) {
		//1、判断登录用户是否超时
		//2、登录用户是否拥有权限
		return new ModelAndView("/marketing/proceeds/deposit").addObject("relationId", payDepositDto.getId());
	}
	
	/**
	 * 进入认筹收款界面
	 * @return
	 */
	@RequestMapping("getPayDepositById")
	public void getPayDepositById(PayDepositDto payDepositDto, HttpServletRequest request, HttpServletResponse response) {
		try {
			ExtResultVo extResultVo = new ExtResultVo();
			extResultVo.setSuccess(false);
			PayDepositDetailVo payDepDetailVo = new PayDepositDetailVo();
			if(payDepositDto.getId() == null){
				extResultVo.setErrorMessage("未找到认筹记录");
			}else{
				//认筹信息
				Response<PayDeposit> resPayDeposit = payDepositServiceFacade.findById(payDepositDto.getId());
				PayDeposit payDeposit = resPayDeposit.getEntity();
				if(payDeposit != null){
					payDepDetailVo.setInfo_depositCode(payDeposit.getDepositCode());
					payDepDetailVo.setInfo_receivable(String.valueOf(payDeposit.getPayDepositAmount()));
					payDepDetailVo.setInfo_remark(payDeposit.getRemark());

					Response<Customer> customerResponse = customerServiceFacade.findById(payDeposit.getCustomerId());
					payDepDetailVo.setCustomerName(customerResponse.getEntity().getCustomerName());
					
					//查询条件: 认筹ID、认筹类型、收款类型
					HaveReceiveRefundDto hrrfDto = new HaveReceiveRefundDto();
					//认筹Id
					hrrfDto.setRelationId(payDepositDto.getId());
					//0认筹 1认购 2签约 3面积补差,和应收款记录保持一致
					hrrfDto.setReceivablesType(ReceivablesTypeEnum.DEPOSIT.getNo());
					//0已收款 1已退款
					hrrfDto.setDocType(DocTypeEnum.COLLECTION.getNo());
					double info_received = haveReceiveRefundServiceFacade.haveReceiveAmount(hrrfDto);
					payDepDetailVo.setInfo_received(String.valueOf(info_received));
					
					//获取登录用户相关信息
					User user = ShiroUtil.getCurrentUser();
					payDepDetailVo.setUserId(user.getId());
					payDepDetailVo.setUserName(user.getUserName());
					payDepDetailVo.setUserCode(user.getUserCode());
					extResultVo.setSuccess(true);
				}else{
					extResultVo.setErrorMessage("未找到认筹记录");
				}
			}
			extResultVo.setData(payDepDetailVo);
			resultJson(response, extResultVo);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("进入认筹收款界面失败", e);
		}
	}
	
	/**
	 * 进入认购收款界面
	 * @return
	 */
	@RequestMapping("subscribe")
	public ModelAndView subscribe(SubscribeDto subscribeDto) {
	    	ModelAndView mv = new ModelAndView("/marketing/proceeds/subscribe").addObject("relationId", subscribeDto.getId());
		return mv;
	}
	
	public Map<String, Boolean> vaild(Long subId){
	    Map<String, Boolean> map = new HashMap<String, Boolean>();
	    Response<Subscribe> subResponse = subscribeServiceFacade.findById(subId);
	    if(subResponse.isSuccess()&&subResponse.getEntity()!=null){
	    	Subscribe subscribe = subResponse.getEntity();
	    	Project project = projectServiceFacade.findById(subscribe.getProjectId()).getEntity();
	    	if(!StringUtils.isEmpty(project.getBindReceivables())&&project.getBindReceivables().equals("0")){
	    	    HaveReceiveRefundDto hrrfDto = new HaveReceiveRefundDto();
    	    	    hrrfDto.setRelationId(subId);
    		    //0认筹 1认购 2签约 3面积补差,和应收款记录保持一致
    	    	    hrrfDto.setReceivablesType(ReceivablesTypeEnum.SUBSCRIBE.getNo());
    	    	    //0已收款 1已退款
    	    	    hrrfDto.setDocType(DocTypeEnum.COLLECTION.getNo());
	    	    double info_received = haveReceiveRefundServiceFacade.haveReceiveAmount(hrrfDto);
	    	    if(subscribe.getDepositReceivable().subtract(new BigDecimal(info_received)).compareTo(BigDecimal.ZERO)==0){
	    		map.put("info", false);
	    	    }else{
	    		map.put("info", true);
	    	    }
	    	}else{
	    	    map.put("info", true);
	    	}
	    }
	    return map;
	}
	
	/**
	 * 进入认购收款界面
	 * @return
	 */
	@RequestMapping("getSubscribeById")
	public void getSubscribeById(SubscribeDto subscribeDto, HttpServletRequest request, HttpServletResponse response) {
		try {
			ExtResultVo extResultVo = new ExtResultVo();
			SubscribeDetailVo subscribeDetailVo = new SubscribeDetailVo();
			if(subscribeDto.getId() == null){
				extResultVo.setSuccess(false);
				extResultVo.setErrorMessage("未找到认购记录");
			}else{
				//认购信息
				Response<Subscribe> resSubscribe = subscribeServiceFacade.findById(subscribeDto.getId());
				Subscribe subscribe = resSubscribe.getEntity();
				if(subscribe != null){
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					if(subscribe.getDueTime() != null){
						subscribeDetailVo.setInfo_dueTime(sdf.format(subscribe.getDueTime()));
					}
					subscribeDetailVo.setInfo_conversionPrice(String.valueOf(subscribe.getConversionPrice()));
					subscribeDetailVo.setInfo_lumpsumPrice(String.valueOf(subscribe.getLumpsumPrice()));
					subscribeDetailVo.setInfo_discountAmount(String.valueOf(subscribe.getDiscountAmount()));
					subscribeDetailVo.setInfo_discountRate(String.valueOf(subscribe.getDiscountRate()));
					subscribeDetailVo.setInfo_discountNote(subscribe.getDiscountNote());
					subscribeDetailVo.setInfo_subscribePrice(String.valueOf(subscribe.getSubscribePrice()));
					subscribeDetailVo.setInfo_subscribeAmount(String.valueOf(subscribe.getSubscribeAmount()));

					Response<Customer> customerResponse = customerServiceFacade.findById(subscribe.getCustomerId());
					subscribeDetailVo.setCustomerName(customerResponse.getEntity().getCustomerName());

					if(subscribe.getSubscribeAmount() != null){
						String subscribeAmount_cn = "";
						subscribeAmount_cn = NumberToCN.number2CNMontrayUnit(new BigDecimal(subscribe.getSubscribeAmount().doubleValue()));
						subscribeDetailVo.setInfo_subscribeAmount_cn(subscribeAmount_cn);
					}
					//已收意向金
					HaveReceiveRefundDto hrrfDto = new HaveReceiveRefundDto();
					double depReceived = 0;
					if(subscribe.getPayDepositId() != null){
						//认筹Id
						hrrfDto.setRelationId(subscribe.getPayDepositId());
						//0认筹 1认购 2签约 3面积补差,和应收款记录保持一致
						hrrfDto.setReceivablesType(ReceivablesTypeEnum.DEPOSIT.getNo());
						//0已收款 1已退款
						hrrfDto.setDocType(DocTypeEnum.COLLECTION.getNo());
						depReceived = haveReceiveRefundServiceFacade.haveReceiveAmount(hrrfDto);
					}
					subscribeDetailVo.setInfo_depositAmount(String.valueOf(depReceived));
					//应收定金,一个做展示,一个用作计算
					subscribeDetailVo.setInfo_depositReceivable(String.valueOf(subscribe.getDepositReceivable()));
					subscribeDetailVo.setInfo_receivable(String.valueOf(subscribe.getDepositReceivable()));
					subscribeDetailVo.setInfo_remark(subscribe.getRemark());
					if(StringUtils.isNotBlank(subscribe.getDealCategory())){
						subscribeDetailVo.setInfo_dealCategory(DealCategoryEnum.getByNo(subscribe.getDealCategory()).getDes());
					}
					if(subscribe.getAgentId() != null){
						Response<User> resAgent = userServiceFacade.findById(subscribe.getAgentId());
						User agent = resAgent.getEntity();
						subscribeDetailVo.setInfo_agentName(agent.getUserName());
					}
					subscribeDetailVo.setInfo_didTime(sdf.format(subscribe.getDidTime()));
					
					//查询已收认购款: 查询参数认筹ID、认筹类型、收款类型
					hrrfDto = new HaveReceiveRefundDto();
					//认筹Id
					hrrfDto.setRelationId(subscribeDto.getId());
					//0认筹 1认购 2签约 3面积补差,和应收款记录保持一致
					hrrfDto.setReceivablesType(ReceivablesTypeEnum.SUBSCRIBE.getNo());
					//0已收款 1已退款
					hrrfDto.setDocType(DocTypeEnum.COLLECTION.getNo());
					double info_received = haveReceiveRefundServiceFacade.haveReceiveAmount(hrrfDto);
					subscribeDetailVo.setInfo_received(String.valueOf(info_received));
					
					//获取登录用户相关信息
					User user = ShiroUtil.getCurrentUser();
					subscribeDetailVo.setUserId(user.getId());
					subscribeDetailVo.setUserName(user.getUserName());
					subscribeDetailVo.setUserCode(user.getUserCode());
					extResultVo.setSuccess(true);
				}else{
					extResultVo.setSuccess(false);
					extResultVo.setErrorMessage("未找到认购记录");
				}
			}
			extResultVo.setData(subscribeDetailVo);
			resultJson(response, extResultVo);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("进入认购收款界面失败", e);
		}
	}
	
	/**
	 * 进入面积补差收款界面
	 * @return
	 */
	@RequestMapping("area")
	public ModelAndView area(ReserveAreaDto reserveAreaDto) {
		return new ModelAndView("/marketing/proceeds/area").addObject("relationId", reserveAreaDto.getId());
	}
	
	/**
	 * 进入面积补差收款界面
	 * @return
	 */
	@RequestMapping("getAreaById")
	public void getAreaById(ReserveAreaDto reserveAreaDto, HttpServletRequest request, HttpServletResponse response) {
		try {
			ExtResultVo extResultVo = new ExtResultVo();
			SignedDetailVo signedDetailVo = new SignedDetailVo();
			if(reserveAreaDto.getId() == null){
				extResultVo.setSuccess(false);
				extResultVo.setErrorMessage("未找到面积补差记录");
			}else{
				Response<ReserveArea> response2 = reserveAreaServiceFacade.findById(reserveAreaDto.getId());
				if(!response2.isSuccess()){
					extResultVo.setSuccess(false);
					extResultVo.setErrorMessage("未找到面积补差记录");
					return;
				}
				ReserveArea reserveArea = response2.getEntity();
				if(reserveArea.getMakeBalance().compareTo(new BigDecimal("0"))>0){ //正数  增加应收
					signedDetailVo.setDocType("0");
				}else{
					signedDetailVo.setDocType("1");
				}
				//签约信息
				Response<Signed> resSigned = signedServiceFacade.findById(reserveArea.getSignedId());
				Signed signed = resSigned.getEntity();
				if(signed != null){
					signedDetailVo.setInfo_signCode(signed.getSignCode());
					signedDetailVo.setInfo_signPrice(String.valueOf(signed.getSignPrice()));
					signedDetailVo.setInfo_signAmount(String.valueOf(signed.getSignAmount()));

					Response<Customer> customerResponse = customerServiceFacade.findById(signed.getCustomerId());
					signedDetailVo.setCustomerName(customerResponse.getEntity().getCustomerName());

					if(signed.getSignAmount() != null){
						String signAmount_cn = "";
						signAmount_cn = NumberToCN.number2CNMontrayUnit(new BigDecimal(signed.getSignAmount().intValue()));
						signedDetailVo.setInfo_signAmount_cn(signAmount_cn);
					}
					if(StringUtils.isNotEmpty(signed.getPaymentMethod())){
						signedDetailVo.setInfo_paymentMethod(PaymentMethodEnum.getByNo(signed.getPaymentMethod()).getDes());
					}
					signedDetailVo.setInfo_receivable(String.valueOf(signed.getSignAmount()));
					
					//认筹已收
					//查询已收认筹款: 查询参数认筹ID、认筹类型、收款类型
					HaveReceiveRefundDto hrrfDto = new HaveReceiveRefundDto();
					double info_depReceived = 0;
					if(signed.getPayDepositId() != null){
						hrrfDto.setRelationId(signed.getPayDepositId());
						hrrfDto.setReceivablesType(ReceivablesTypeEnum.DEPOSIT.getNo());
						hrrfDto.setDocType(DocTypeEnum.COLLECTION.getNo());
						info_depReceived = haveReceiveRefundServiceFacade.haveReceiveAmount(hrrfDto);
					}
					signedDetailVo.setInfo_depReceived(String.valueOf(info_depReceived));
					
					//认购已收
					//查询已收认购款: 查询参数认购ID、认购类型、收款类型
					hrrfDto = new HaveReceiveRefundDto();
					double info_subReceived = 0;
					if(signed.getSubscribeId() != null){
						hrrfDto.setRelationId(signed.getSubscribeId());
						hrrfDto.setReceivablesType(ReceivablesTypeEnum.SUBSCRIBE.getNo());
						hrrfDto.setDocType(DocTypeEnum.COLLECTION.getNo());
						info_subReceived = haveReceiveRefundServiceFacade.haveReceiveAmount(hrrfDto);
					}
					signedDetailVo.setInfo_subReceived(String.valueOf(info_subReceived));
					
					//签约已收
					//查询已收签约款: 查询参数签约ID、签约类型、收款类型
					hrrfDto = new HaveReceiveRefundDto();
					hrrfDto.setRelationId(signed.getId());
					hrrfDto.setReceivablesType(ReceivablesTypeEnum.SIGNED.getNo());
					hrrfDto.setDocType(DocTypeEnum.COLLECTION.getNo());
					double info_signedReceived = haveReceiveRefundServiceFacade.haveReceiveAmount(hrrfDto);
					signedDetailVo.setInfo_signedReceived(String.valueOf(info_signedReceived));
					
					//已收金额 = 签约已收+认筹已收+认购已收
					double info_received = info_depReceived + info_subReceived + info_signedReceived;
					signedDetailVo.setInfo_received(String.valueOf(info_received));
					
					//总未收金额 = 总合同金额 - 已收金额
					signedDetailVo.setInfo_unReceived(String.valueOf(signed.getSignAmount().subtract(BigDecimal.valueOf(info_received))));
					
					//获取登录用户相关信息
					User user = ShiroUtil.getCurrentUser();
					signedDetailVo.setUserId(user.getId());
					signedDetailVo.setUserName(user.getUserName());
					signedDetailVo.setUserCode(user.getUserCode());
					extResultVo.setSuccess(true);
				}else{
					extResultVo.setSuccess(false);
					extResultVo.setErrorMessage("未找到认购记录");
				}
			}
			extResultVo.setData(signedDetailVo);
			resultJson(response, extResultVo);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("进入面积补差收款界面失败", e);
		}
	}
	
	/**
	 * 面积补差待收款记录
	 * @param dto
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="areaList")
	@ResponseBody
    public List<NeedReceiveRefundDto> areaList(NeedReceiveRefundDto dto, HttpServletRequest request, HttpServletResponse response){
		List<NeedReceiveRefundDto> returnList = new ArrayList<NeedReceiveRefundDto>();
    	try {
    		ResponseList<NeedReceiveRefundDto> resList = needReceiveRefundServiceFacade.findNrrfDtoByDto(dto);

			Response<ReserveArea> response2 = reserveAreaServiceFacade.findById(dto.getRelationId());
			ReserveArea reserveArea = null;
			if(response2.isSuccess()){
				reserveArea = response2.getEntity();
				dto.setRelationId(reserveArea.getSignedId());
			}
    		ResponseList<NeedReceiveRefundDto> resList2 = needReceiveRefundServiceFacade.findNrrfDtoByDto(dto);
    		
            if(resList.isSuccess()){
            	returnList = resList.getEntity();
            	if(resList.isSuccess()){
            		returnList.removeAll(resList2.getEntity());
            		returnList.addAll(resList2.getEntity());
            	}
            	if(returnList.size() > 0){
            		for(NeedReceiveRefundDto nrrfDto: returnList){
            			BigDecimal total = nrrfDto.getTotalReceivablesAmount();
            			BigDecimal received = nrrfDto.getHaveReceivedTotal()==null?(new BigDecimal(0)):nrrfDto.getHaveReceivedTotal();
            			nrrfDto.setHaveReceivedTotal(received);
            			BigDecimal unReceived = total.subtract(received);
            			nrrfDto.setUnReceivedTotal(unReceived);
            		}
            	}
            }
		} catch (Exception e) {
			logger.error("面积补差待收款记录 areaList", e);
		
		}
    	return returnList;
    }

	/**
	 * 进入垫付首期收款界面
	 * @return
	 */
	@RequestMapping("advance")
	public ModelAndView advance(Long id) {
		Response<NeedAdvanceRefund> advanceRefundResponse = needAdvanceRefundServiceFacade.findById(id);
		NeedAdvanceRefund needAdvanceRefund = advanceRefundResponse.getEntity();
		return new ModelAndView("/marketing/proceeds/advance").addObject("relationId", needAdvanceRefund.getRelationId()).addObject("advanceId", id);
	}

	/**
	 * 进入垫付首期收款界面
	 * @return
	 */
	@RequestMapping("getAdvanceById")
	public void getAdvanceById(Long id, HttpServletRequest request, HttpServletResponse response) {
		try {
			ExtResultVo extResultVo = new ExtResultVo();
			SignedDetailVo signedDetailVo = new SignedDetailVo();
			if(id == null){
				extResultVo.setSuccess(false);
				extResultVo.setErrorMessage("未找到垫付首期记录");
			}else{
				Response<NeedAdvanceRefund> advanceRefundResponse = needAdvanceRefundServiceFacade.findById(id);
				NeedAdvanceRefund needAdvanceRefund = advanceRefundResponse.getEntity();
				signedDetailVo.setAdvanceNeedTotal(needAdvanceRefund.getTotalReceivablesAmount().toString());
				signedDetailVo.setNeedReceiveId(needAdvanceRefund.getId());

				Response<BigDecimal> advanceHaveTotalResponse = haveAdvanceRefundServiceFacade.findHaveAmount(id);
				signedDetailVo.setAdvanceHaveTotal(advanceHaveTotalResponse.getEntity().toString());

				//签约信息
				Response<Signed> resSigned = signedServiceFacade.findById(needAdvanceRefund.getRelationId());
				Signed signed = resSigned.getEntity();
				if(signed != null){
					signedDetailVo.setInfo_signCode(signed.getSignCode());
					signedDetailVo.setInfo_signPrice(String.valueOf(signed.getSignPrice()));
					signedDetailVo.setInfo_signAmount(String.valueOf(signed.getSignAmount()));

					Response<Customer> customerResponse = customerServiceFacade.findById(signed.getCustomerId());
					signedDetailVo.setCustomerName(customerResponse.getEntity().getCustomerName());

					if(signed.getSignAmount() != null){
						String signAmount_cn = "";
						signAmount_cn = NumberToCN.number2CNMontrayUnit(new BigDecimal(signed.getSignAmount().intValue()));
						signedDetailVo.setInfo_signAmount_cn(signAmount_cn);
					}
					if(StringUtils.isNotEmpty(signed.getPaymentMethod())){
						signedDetailVo.setInfo_paymentMethod(PaymentMethodEnum.getByNo(signed.getPaymentMethod()).getDes());
					}
					if(StringUtils.isNotEmpty(signed.getDecorationPaymentMethod())){
						signedDetailVo.setInfo_decorationPaymentMethod(DecorationPaymentMethodEnum.getByNo(signed.getDecorationPaymentMethod()).getDes());
					}
					//合同金额加上装修款
					signedDetailVo.setInfo_receivable(String.valueOf(signed.getSignAmount().add(decorationMoney(needAdvanceRefund.getRelationId()))));

					//签约已收
					//查询已收签约款: 查询参数签约ID、签约类型、收款类型
					HaveReceiveRefundDto hrrfDto = new HaveReceiveRefundDto();
					hrrfDto.setRelationId(signed.getId());
					hrrfDto.setReceivablesType(ReceivablesTypeEnum.SIGNED.getNo());
					hrrfDto.setDocType(DocTypeEnum.COLLECTION.getNo());
					double info_signedReceived = haveReceiveRefundServiceFacade.haveReceiveAmount(hrrfDto);

					//签约已收金额
					signedDetailVo.setInfo_received(String.valueOf(info_signedReceived));

					//总未收金额 = 合同金额 + 装修款 - 已收金额
					BigDecimal info_unReceived = signed.getSignAmount()
//							.add(signed.getDecorationMoney() == null?new BigDecimal("0"):signed.getDecorationMoney())
							.subtract(BigDecimal.valueOf(info_signedReceived));
					signedDetailVo.setInfo_unReceived(String.valueOf(info_unReceived));

					//获取登录用户相关信息
					User user = ShiroUtil.getCurrentUser();
					signedDetailVo.setUserId(user.getId());
					signedDetailVo.setUserName(user.getUserName());
					signedDetailVo.setUserCode(user.getUserCode());
					extResultVo.setSuccess(true);
				}else{
					extResultVo.setSuccess(false);
					extResultVo.setErrorMessage("未找到签约记录");
				}
			}
			extResultVo.setData(signedDetailVo);
			resultJson(response, extResultVo);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("进入签约收款界面失败", e);
		}
	}
	
	/**
	 * 进入签约收款界面
	 * @return
	 */
	@RequestMapping("signed")
	public ModelAndView signed(SignedDto signedDto) {
		return new ModelAndView("/marketing/proceeds/signed").addObject("relationId", signedDto.getId());
	}
	
	/**
	 * 进入签约收款界面
	 * @return
	 */
	@RequestMapping("getSignedById")
	public void getSignedById(SignedDto signedDto, HttpServletRequest request, HttpServletResponse response) {
		try {
			ExtResultVo extResultVo = new ExtResultVo();
			SignedDetailVo signedDetailVo = new SignedDetailVo();
			if(signedDto.getId() == null){
				extResultVo.setSuccess(false);
				extResultVo.setErrorMessage("未找到签约记录");
			}else{
				//签约信息
				Response<Signed> resSigned = signedServiceFacade.findById(signedDto.getId());
				Signed signed = resSigned.getEntity();
				if(signed != null){
					signedDetailVo.setInfo_signCode(signed.getSignCode());
					signedDetailVo.setInfo_signPrice(String.valueOf(signed.getSignPrice()));
					signedDetailVo.setInfo_signAmount(String.valueOf(signed.getSignAmount()));

					Response<Customer> customerResponse = customerServiceFacade.findById(signed.getCustomerId());
					signedDetailVo.setCustomerName(customerResponse.getEntity().getCustomerName());

					if(signed.getSignAmount() != null){
						String signAmount_cn = "";
						signAmount_cn = NumberToCN.number2CNMontrayUnit(new BigDecimal(signed.getSignAmount().intValue()));
						signedDetailVo.setInfo_signAmount_cn(signAmount_cn);
					}
					if(StringUtils.isNotEmpty(signed.getPaymentMethod())){
						signedDetailVo.setInfo_paymentMethod(PaymentMethodEnum.getByNo(signed.getPaymentMethod()).getDes());
					}
					if(StringUtils.isNotEmpty(signed.getDecorationPaymentMethod())){
						signedDetailVo.setInfo_decorationPaymentMethod(DecorationPaymentMethodEnum.getByNo(signed.getDecorationPaymentMethod()).getDes());
					}
					//合同金额加上装修款
					signedDetailVo.setInfo_receivable(String.valueOf(signed.getSignAmount().add(decorationMoney(signedDto.getId()))));
					
					//签约已收
					//查询已收签约款: 查询参数签约ID、签约类型、收款类型
					HaveReceiveRefundDto	hrrfDto = new HaveReceiveRefundDto();
					hrrfDto.setRelationId(signed.getId());
					hrrfDto.setReceivablesType(ReceivablesTypeEnum.SIGNED.getNo());
					hrrfDto.setDocType(DocTypeEnum.COLLECTION.getNo());
					double info_signedReceived = haveReceiveRefundServiceFacade.haveReceiveAmount(hrrfDto);
					
					//签约已收金额
					signedDetailVo.setInfo_received(String.valueOf(info_signedReceived));
					
					//总未收金额 = 合同金额 + 装修款 - 已收金额
					BigDecimal info_unReceived = signed.getSignAmount()
//							.add(signed.getDecorationMoney() == null?new BigDecimal("0"):signed.getDecorationMoney())
							.subtract(BigDecimal.valueOf(info_signedReceived));
					signedDetailVo.setInfo_unReceived(String.valueOf(info_unReceived));
					
					//获取登录用户相关信息
					User user = ShiroUtil.getCurrentUser();
					signedDetailVo.setUserId(user.getId());
					signedDetailVo.setUserName(user.getUserName());
					signedDetailVo.setUserCode(user.getUserCode());
					extResultVo.setSuccess(true);
				}else{
					extResultVo.setSuccess(false);
					extResultVo.setErrorMessage("未找到认购记录");
				}
			}
			extResultVo.setData(signedDetailVo);
			resultJson(response, extResultVo);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("进入签约收款界面失败", e);
		}
	}
	//查询装修款，没有则返回0
	private BigDecimal decorationMoney(Long id) {
		BigDecimal decorationMoney = new BigDecimal("0");
		NeedReceiveRefundDto needDto = new NeedReceiveRefundDto();
		needDto.setRelationId(id);
		needDto.setBusinessType(ReceivablesTypeEnum.SIGNED.getNo());
		needDto.setDocType(DocTypeEnum.COLLECTION.getNo());
		ResponseList<NeedReceiveRefund> resNeed = needReceiveRefundServiceFacade.findByDto(needDto);
		if(resNeed.isSuccess() && resNeed.getEntity() != null) {
			for(NeedReceiveRefund need : resNeed.getEntity()) {
				if(HousingFundTypeEnum.getByNo(need.getHousingFundType()).getDes().indexOf("装修款") >= 0 ) {
					decorationMoney = need.getTotalReceivablesAmount();
				}
			}
		}
		return decorationMoney;
	}
	
	/**
	 * 签约待收款记录
	 * @param dto
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="needList")
	@ResponseBody
    public List<NeedReceiveRefundDto> list(NeedReceiveRefundDto dto, HttpServletRequest request, HttpServletResponse response){
		List<NeedReceiveRefundDto> returnList = new ArrayList<NeedReceiveRefundDto>();
    	try {
    		ResponseList<NeedReceiveRefundDto> resList = needReceiveRefundServiceFacade.findNrrfDtoByDto(dto);
    	//  NeedReceiveRefundDto nrrfDto: returnList
            if(resList.isSuccess()){
            	returnList = resList.getEntity();
            	if(returnList.size() > 0){
            		for(int i=0;i<returnList.size();i++){
            			NeedReceiveRefundDto nrrfDto= returnList.get(i);
            			Response<BigDecimal> res = haveReceiveRefundServiceFacade.findHaveAmount(nrrfDto.getId());
            				if(res.isSuccess()){
            					nrrfDto.setHaveReceivedTotal(res.getEntity());
            					nrrfDto.setUnReceivedTotal(nrrfDto.getTotalReceivablesAmount().subtract(res.getEntity()));
            				}
            		}
            	}
            }
            //面积补差款
            NeedReceiveRefundDto areaNeed = new NeedReceiveRefundDto();
            areaNeed.setRelationId(dto.getRelationId());
            areaNeed.setDocType("0");
            areaNeed.setBusinessType("3");
            ResponseList<NeedReceiveRefund> refund =  needReceiveRefundServiceFacade.findByDto(areaNeed);
            
            if(refund.isSuccess()){
            	if(null!=refund.getEntity()){
            		for (NeedReceiveRefund needs:refund.getEntity()) {
            			NeedReceiveRefundDto dtos = new NeedReceiveRefundDto();
            			BeanUtil.convert2T(dtos, needs);
            			Response<BigDecimal> res = haveReceiveRefundServiceFacade.findHaveAmount(needs.getId());
            			if(res.isSuccess()){
            				dtos.setHaveReceivedTotal(res.getEntity());
            				dtos.setUnReceivedTotal(dtos.getTotalReceivablesAmount().subtract(res.getEntity()));
            				resList.getEntity().add(dtos);
        				}
					}
            	}
            }
            
		} catch (Exception e) {
			logger.error("签约待收款记录 needList", e);
		
		}
    	return returnList;
    }
	
	/**
	 * 签约待收款记录
	 * @param dto
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="needDropDownList")
	@ResponseBody
    public RootClass needDropDownList(NeedReceiveRefundDto dto, HttpServletRequest request, HttpServletResponse response){
		RootClass root = new RootClass();
    	try {
    		//不展示收款成功的记录
    		//dto.setStatus(NeedStatusEnum.NO.getNo());
    		ResponseList<NeedReceiveRefundDto> resList = needReceiveRefundServiceFacade.findNrrfDtoByDto(dto);
            if(resList.isSuccess()){
        		root.setRoot(resList.getEntity());
            }
		} catch (Exception e) {
			logger.error("签约待收款记录 needDropDownList", e);
		}
    	return root;
    }
	
	@RequestMapping("proceeds")
	public void proceeds(ProceedsDto proceedsDto, HttpServletRequest request, HttpServletResponse response){
		ExtResultVo extResultVo = new ExtResultVo();
		Map<String, String> returnMap = new HashMap<String, String>();
		try{
			returnMap = proceedsServiceFacade.receiveMoney(proceedsDto);
			if("00000".equals(returnMap.get("returnCode"))){
				extResultVo.setSuccess(false);
				extResultVo.setErrorMessage(returnMap.get("returnMsg"));
			}else if("00001".equals(returnMap.get("returnCode"))){
				extResultVo.setSuccess(true);
				extResultVo.setErrorMessage(returnMap.get("returnMsg"));
			}
			resultJson(response, extResultVo);
		}catch (Exception e) {
			logger.error("收款错误: [收款类型: "+proceedsDto.getBusinessType()+"]、[收款编号: "+proceedsDto.getRelationId()+"]、[错误信息:"+e.getMessage()+"]");
			e.printStackTrace();
			try {
				extResultVo.setErrorMessage(e.getMessage());
				resultJson(response, extResultVo);
			} catch (IOException e1) {
				logger.error("proceeds error: ", e1);
				
			}
		}
	}

	@RequestMapping("advanceProceeds")
	public void advanceProceeds(ProceedsDto proceedsDto, HttpServletRequest request, HttpServletResponse response){
		ExtResultVo extResultVo = new ExtResultVo();
		Map<String, String> returnMap = new HashMap<String, String>();
		try{
			returnMap = proceedsServiceFacade.receiveAdvanceMoney(proceedsDto);
			if("00000".equals(returnMap.get("returnCode"))){
				extResultVo.setSuccess(false);
				extResultVo.setErrorMessage(returnMap.get("returnMsg"));
			}else if("00001".equals(returnMap.get("returnCode"))){
				extResultVo.setSuccess(true);
				extResultVo.setErrorMessage(returnMap.get("returnMsg"));
			}
			resultJson(response, extResultVo);
		}catch (Exception e) {
			logger.error("收款错误: [收款类型: "+proceedsDto.getBusinessType()+"]、[收款编号: "+proceedsDto.getRelationId()+"]、[错误信息:"+e.getMessage()+"]");
			e.printStackTrace();
			try {
				extResultVo.setErrorMessage(e.getMessage());
				resultJson(response, extResultVo);
			} catch (IOException e1) {
				logger.error("proceeds error: ", e1);

			}
		}
	}
}
